/*
 *  gate.c 
 * 
 */

/* 
 * device specifics, such as ioctl numbers and the
 * major device file. 
 */
#include "drivergate.h"

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>		/* open */
#include <unistd.h>		/* exit */
#include <sys/ioctl.h>		/* ioctl */

/* 
 * Functions for the ioctl calls 
 */

int ioctl_open_gate(int file_desc)
{
	int ret_val;

	ret_val = ioctl(file_desc, GATE_OPEN, NULL);

	if (ret_val < 0) {
		printf("gate_open failed:%d\n", ret_val);
		return -1;
	}
	return 0;
}

int ioctl_close_gate(int file_desc)
{
	int ret_val;

	ret_val = ioctl(file_desc, GATE_CLOSE, NULL);

	if (ret_val < 0) {
		printf("gate_close failed:%d\n", ret_val);
		return -1;
	}
	return 0;
}

int ioctl_gate_status(int file_desc)
{
	int* status;
	int ret_val;

	ret_val = ioctl(file_desc, GATE_STATUS, status);

	if (ret_val < 0) {
		printf("gate_close failed:%d\n", ret_val);
		exit(-1);
	}
	return *status;
}



/* 
 * Main - Call the ioctl functions 
 */
int main(int argc, char **argv)
{
	int file_desc;
	char *msg;
	int loop = 1;
	char option[128];
	int status;
	file_desc = open(DEVICE_FILE_NAME, 0);
	if (file_desc < 0) {
		printf("Can't open device file: %s\n", DEVICE_FILE_NAME);
		exit(-1);
	}
	
	while(loop)
	{
		printf("(o)pen, (c)lose, (s)tatus, (q)uit\n");
		scanf("%s", &option[0]);
		if (option[0] == 'o')
		{
			printf("Gate Opened!\n");
			msg = "The gate is open";
			ioctl_open_gate(file_desc);
		}
		else if (option[0] == 'c')
		{
			printf("Gate Closed!\n");
			msg = "The gate is closed";
			ioctl_close_gate(file_desc);
		}
		else if	(option[0] == 's')
		{
			status = ioctl_gate_status(file_desc);
		if(status == 0)
			printf("Status: Close.\n");
		else
			printf("Status: Open.\n");
		}
		else if (option[0] == 'q')
			loop = 0;	
		else
			printf("Invalid option\n");	
	}
	close(file_desc);
	exit(0);
}
